package com.easipass.lgsa.portRelease.util;

import com.easipass.bscp.dto.*;
import com.google.gson.Gson;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/*
 * 引入坐标
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.9</version>
</dependency>
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext-asian</artifactId>
    <version>5.2.0</version>
</dependency>
<dependency>
    <groupId>com.itextpdf.tool</groupId>
    <artifactId>xmlworker</artifactId>
    <version>5.5.9</version>
</dependency>
*/

@Component
public class PdfUtil {

    @Autowired
    private ParamUtil paramUtil;
    private final Log log = LogFactory.getLog(this.getClass());
    private Gson gson = new Gson();
    /**
     * 关区表参数redis前缀
     */
    private static final String REDIS_PARAM_CUSTOMS_PREFIX = "param_customs_";

    /**
     * 国别表参数redis前缀
     */
    private static final String REDIS_PARAM_COUNTRY_PREFIX = "param_country_";

    /**
     * 币制参数redis前缀
     */
    public static final String REDIS_PARAM_CURR_PREFIX = "param_curr_";

    /**
     * 计量单位表参数redis前缀
     */
    public static final String REDIS_PARAM_UNIT_PREFIX = "param_unit_";


    private void tableAddCell(PdfPTable table, Font fontsize, String key, String value) {
        PdfPCell cell = null;
        cell = new PdfPCell();
        cell.setMinimumHeight(18f);
        cell.setPhrase(new Paragraph(key, fontsize));
        table.addCell(cell);

        cell = new PdfPCell();
        cell.setMinimumHeight(18f);
        cell.setPhrase(new Paragraph(value, fontsize));
        table.addCell(cell);
    }

    private void tableAddCell(PdfPTable table, Font fontsize, String value) {
        PdfPCell cell = null;
        cell = new PdfPCell();
        cell.setMinimumHeight(18f);
        cell.setPhrase(new Paragraph(value, fontsize));
        table.addCell(cell);
    }

    public void downPdfHfd(HttpServletResponse response, List<PortReleaseBsc> bscList, String fileName) throws Exception {
        // 告诉浏览器用什么软件可以打开此文件
        response.setHeader("content-Type", "application/pdf");
        // 下载文件的默认名称
        if (bscList.size() == 1) {
            fileName = java.net.URLEncoder.encode(fileName, "UTF-8") + "_" + bscList.get(0).getPreentNo() + ".pdf";
        } else {
            fileName = java.net.URLEncoder.encode(fileName, "UTF-8") + "_" + dateToString(new Date(), "yyyyMMddHHmmss") + ".pdf";
        }
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        Document document = new Document(PageSize.A4, -10, -10, 50, 50);
        PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
        writer.setEncryption(null, null, PdfWriter.ALLOW_PRINTING, PdfWriter.STANDARD_ENCRYPTION_128);
        // 支持中文
        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);

        // 设置字体
        Font fontsize08 = new Font(bfChinese, 8, Font.NORMAL);
        Font fontsize09 = new Font(bfChinese, 10, Font.BOLD);
        Font fontsize10 = new Font(bfChinese, 10, Font.NORMAL);
        Font fontsize12 = new Font(bfChinese, 12, Font.NORMAL);
        Font fontsize15 = new Font(bfChinese, 15, Font.NORMAL);

        PdfPTable table = null;
        PdfPCell cell = null;

        document.open();

        for (PortReleaseBsc dto : bscList) {
            table = new PdfPTable(3);

            //新增一行
            // 条形码
            /*if (dto.getPreentNo() != null) {
                PdfContentByte cds = writer.getDirectContent();
                Barcode128 code128s = new Barcode128();
                code128s.setCode(dto.getPreentNo());
                Image image128s = code128s.createImageWithBarcode(cds, null, null);
                PdfPCell barcodeCells = new PdfPCell(image128s);
                barcodeCells.setMinimumHeight(8f);
                barcodeCells.setBorder(PdfPCell.NO_BORDER);
                barcodeCells.setHorizontalAlignment(Element.ALIGN_LEFT);
                barcodeCells.setVerticalAlignment(Element.ALIGN_TOP);
                table.addCell(barcodeCells);


                cell = new PdfPCell();
                cell.setBorder(PdfPCell.NO_BORDER);
                cell.setPhrase(new Paragraph("", fontsize08));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setPadding(15);
                table.addCell(cell);

                cell = new PdfPCell();
                cell.setBorder(PdfPCell.NO_BORDER);
                cell.setPhrase(new Paragraph("", fontsize08));

                table.addCell(cell);
            }*/


            // 第一行
            table = new PdfPTable(3);
            cell = new PdfPCell();
            cell.setBorder(PdfPCell.NO_BORDER);
            cell.setPhrase(new Paragraph("", fontsize10));
            table.addCell(cell);

            cell = new PdfPCell();
            cell.setBorder(PdfPCell.NO_BORDER);
            cell.setPhrase(new Paragraph("卡口验放凭证", fontsize15));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setPadding(15);
            table.addCell(cell);

            cell = new PdfPCell();
            cell.setBorder(PdfPCell.NO_BORDER);
            cell.setPhrase(new Paragraph("", fontsize12));
            table.addCell(cell);

            document.add(table);

            table =new PdfPTable(3);
            // 第二行
            cell = new PdfPCell();
            cell.setMinimumHeight(30f);
            cell.setBorder(PdfPCell.NO_BORDER);
            cell.setPhrase(new Paragraph("仅供核对使用", fontsize10));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
            table.addCell(cell);

            // 条形码
            PdfContentByte cd = writer.getDirectContent();
            Barcode128 code128 = new Barcode128();
            code128.setCode(dto.getPreentNo());
            //code128.setX(1.1f);
            //code128.setBarHeight(30f);
            Image image128 = code128.createImageWithBarcode(cd, null, null);
            PdfPCell barcodeCell = new PdfPCell(image128);
            barcodeCell.setBorder(PdfPCell.NO_BORDER);
            barcodeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(barcodeCell);

            cell = new PdfPCell();
            cell.setBorder(PdfPCell.NO_BORDER);
            cell.setPhrase(new Paragraph("打印日期:  " + dateToString(new Date(), "yyyy-MM-dd"), fontsize10));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
            table.addCell(cell);

            document.add(table);

            // 第二个table带边框
            // 第1行
            table = new PdfPTable(6);
            tableAddCell(table, fontsize08, "预录入编号", dto.getPreentNo());
            tableAddCell(table, fontsize08, "出入库类型", Toos.IN_EXP_TYPE_MAP.get(dto.getInExpType()));
            tableAddCell(table, fontsize08, "进出标志", Toos.IE_TYPECD_MAP.get(dto.getIeTypecd()));

            // 第2行
            if (StringUtils.isNotBlank(dto.getBindTypecd())) {
                tableAddCell(table, fontsize08, "绑定类型", Toos.BIND_TYPECD_MAP.get(dto.getBindTypecd()));
            } else {
                tableAddCell(table, fontsize08, "绑定类型", "  ");
            }
            tableAddCell(table, fontsize08, "进出境关别", paramUtil.getcustomsMap().get(REDIS_PARAM_CUSTOMS_PREFIX + dto.getImpexpPortcd()).getCustomName());
            tableAddCell(table, fontsize08, "主管海关", paramUtil.getcustomsMap().get(REDIS_PARAM_CUSTOMS_PREFIX + dto.getMasterCuscd()).getCustomName());

            // 第3行
            tableAddCell(table, fontsize08, "经营企业编码", dto.getBizopEtpsNo());
            tableAddCell(table, fontsize08, "经营企业名称", dto.getBizopEtpsNm());
            tableAddCell(table, fontsize08, "经营企业社会信息用代码", dto.getBizopEtpsSccd());

            // 第4行
            tableAddCell(table, fontsize08, "境内收发货企业编码", dto.getRcvgdEtpsNo());
            tableAddCell(table, fontsize08, "境内收发货企企业名称", dto.getRcvgdEtpsNm());
            tableAddCell(table, fontsize08, "境内收发货企企业社会信息用代码", dto.getRcvgdEtpsSccd());

            // 第5行
            if (StringUtils.isNotBlank(dto.getMtpckEndprdTypecd())) {
                tableAddCell(table, fontsize08, "料件/成品标志", Toos.MTPCK_ENDPRT_TYPECD_MAP.get(dto.getMtpckEndprdTypecd()));
            } else {
                tableAddCell(table, fontsize08, "料件/成品标志", "  ");
            }
            tableAddCell(table, fontsize08, "申报日期", dto.getDclTime());
            tableAddCell(table, fontsize08, "承运车车牌号", dto.getVehicleNo());

            // 第6行
            tableAddCell(table, fontsize08, "集装箱号", dto.getContainerNo());
            tableAddCell(table, fontsize08, "车自重", dto.getVehicleWt());
            tableAddCell(table, fontsize08, "车架号", dto.getVehicleFrameNo());

            // 第7行
            tableAddCell(table, fontsize08, "车架重", dto.getVehicleFrameWt());
            tableAddCell(table, fontsize08, "集装箱型", dto.getContainerType());
            tableAddCell(table, fontsize08, "集装箱重", dto.getContainerWt());

            // 第8行
            tableAddCell(table, fontsize08, "货物总毛重", dto.getTotalGrossWt());
            tableAddCell(table, fontsize08, "货物总净重", dto.getTotalNetWt());
            tableAddCell(table, fontsize08, "总重量", dto.getTotalWt());

            // 第9行
            tableAddCell(table, fontsize08, "备注");
            cell = new PdfPCell();
            cell.setPhrase(new Paragraph(dto.getRmk(), fontsize08));
            cell.setColspan(5);
            table.addCell(cell);


            document.add(table);
            List<PortReleaseRlt> rltList = dto.getPortReleaseRlt();
            if (rltList != null && rltList.size() > 0) {
                //第三个table
                //第一行
                table = new PdfPTable(2);
                cell = new PdfPCell();
                cell.setMinimumHeight(18f);
                cell.setPhrase(new Paragraph("关联单证", fontsize09));
                cell.setColspan(2);
                table.addCell(cell);

                // 第2行
                //tableAddCell(table, fontsize08, "序号");
                tableAddCell(table, fontsize08, "单证类型");
                tableAddCell(table, fontsize08, "关联单证编号");


                //循环
                for (PortReleaseRlt rlt : rltList) {
                    //tableAddCell(table, fontsize08, "$参数1");
                    if (("1").equals(rlt.getRltTbTypecd())) {
                        tableAddCell(table, fontsize08, "进出区提发货凭证");
                    } else if (("2").equals(rlt.getRltTbTypecd())) {
                        tableAddCell(table, fontsize08, "进境径予放行自主声明");
                    } else if (("3").equals(rlt.getRltTbTypecd())) {
                        tableAddCell(table, fontsize08, "出境径予放行自主声明");
                    }
                    tableAddCell(table, fontsize08, rlt.getRltNo());
                }
                document.add(table);
            }

            List<PortReleaseDt> dtList = dto.getPortReleaseDt();
            //如果存在表体
            if (dtList != null && dtList.size() > 0) {
                if ("3".equals(dto.getInExpType())) {
                    //第二个table
                    //第一行
                    table = new PdfPTable(8);
                    int[] widths = {6, 14, 12, 36, 10, 15, 8, 10};
                    table.setWidths(widths);
                    cell = new PdfPCell();
                    cell.setMinimumHeight(18f);
                    cell.setPhrase(new Paragraph("表体", fontsize09));
                    cell.setColspan(8);
                    table.addCell(cell);

                    // 第2行
                    tableAddCell(table, fontsize08, "序号");
                    tableAddCell(table, fontsize08, "商品料号");
                    tableAddCell(table, fontsize08, "商品编码");
                    tableAddCell(table, fontsize08, "商品名称及规格型号");
                    tableAddCell(table, fontsize08, "币制");
                    tableAddCell(table, fontsize08, "申报数量/单位");
                    tableAddCell(table, fontsize08, "原产国(地区)");
                    tableAddCell(table, fontsize08, "净重");
                    //循环
                    for (PortReleaseDt dt : dtList) {
                        tableAddCell(table, fontsize08, dt.getGdsSeqno());
                        tableAddCell(table, fontsize08, dt.getGdsMtno());
                        tableAddCell(table, fontsize08, dt.getGdecd());
                        tableAddCell(table, fontsize08, dt.getGdsNm() + "\n" + (StringUtils.isNotBlank(dt.getGdsSpcfModelDesc()) ? dt.getGdsSpcfModelDesc() : " "));
                        tableAddCell(table, fontsize08, StringUtils.isNotBlank(dt.getDclCurrcd()) ? paramUtil.getCurrMap().get(REDIS_PARAM_CURR_PREFIX + dt.getDclCurrcd()).getCurrName() : " ");
                        tableAddCell(table, fontsize08, dt.getDclQty() + (StringUtils.isNotBlank(dt.getDclUnitcd()) ? paramUtil.getUnitMap().get(REDIS_PARAM_UNIT_PREFIX + dt.getDclUnitcd()).getUnitName() : " "));
                        tableAddCell(table, fontsize08, paramUtil.getCountryMap().get(REDIS_PARAM_COUNTRY_PREFIX + dt.getNatcd()).getNameCn());
                        tableAddCell(table, fontsize08, dt.getNetWt());
                    }
                    document.add(table);
                } else {
                    //第二个table
                    //第一行
                    table = new PdfPTable(9);
                    int[] widths = {16, 6, 14, 12, 34, 10, 15, 8, 10};
                    table.setWidths(widths);
                    cell = new PdfPCell();
                    cell.setMinimumHeight(18f);
                    cell.setPhrase(new Paragraph("表体", fontsize09));
                    cell.setColspan(9);
                    table.addCell(cell);

                    // 第2行
                    tableAddCell(table, fontsize08, "关联单证编号及关联明细序号");
                    tableAddCell(table, fontsize08, "序号");
                    tableAddCell(table, fontsize08, "商品料号");
                    tableAddCell(table, fontsize08, "商品编码");
                    tableAddCell(table, fontsize08, "商品名称及规格型号");
                    tableAddCell(table, fontsize08, "币制");
                    tableAddCell(table, fontsize08, "申报数量/单位");
                    tableAddCell(table, fontsize08, "原产国(地区)");
                    tableAddCell(table, fontsize08, "净重");
                    //循环
                    for (PortReleaseDt dt : dtList) {
                        tableAddCell(table, fontsize08, dt.getRltNo() + "\n" + dt.getRltSeqno());
                        tableAddCell(table, fontsize08, dt.getGdsSeqno());
                        tableAddCell(table, fontsize08, dt.getGdsMtno());
                        tableAddCell(table, fontsize08, dt.getGdecd());
                        tableAddCell(table, fontsize08, dt.getGdsNm() + "\n" + (StringUtils.isNotBlank(dt.getGdsSpcfModelDesc()) ? dt.getGdsSpcfModelDesc() : " "));
                        tableAddCell(table, fontsize08, StringUtils.isNotBlank(dt.getDclCurrcd()) ? paramUtil.getCurrMap().get(REDIS_PARAM_CURR_PREFIX + dt.getDclCurrcd()).getCurrName() : " ");
                        tableAddCell(table, fontsize08, dt.getDclQty() + (StringUtils.isNotBlank(dt.getDclUnitcd()) ? paramUtil.getUnitMap().get(REDIS_PARAM_UNIT_PREFIX + dt.getDclUnitcd()).getUnitName() : " "));
                        tableAddCell(table, fontsize08, paramUtil.getCountryMap().get(REDIS_PARAM_COUNTRY_PREFIX + dt.getNatcd()).getNameCn());
                        tableAddCell(table, fontsize08, dt.getNetWt());
                    }
                    document.add(table);
                }

            }

            /*List<PortReleaseInexpRlt> inexpRltList = dto.getPortReleaseInexpRlt();
            if (null != inexpRltList && inexpRltList.size() > 0) {
                table = new PdfPTable(2);
                cell = new PdfPCell();
                cell.setMinimumHeight(18f);
                cell.setPhrase(new Paragraph("出入库关联单证", fontsize09));
                cell.setColspan(2);
                table.addCell(cell);

                tableAddCell(table,fontsize08,"出入库编号");
                tableAddCell(table,fontsize08,"出入库日期");
                for (PortReleaseInexpRlt inexpRlt : inexpRltList) {
                    tableAddCell(table,fontsize08,inexpRlt.getInExpWhNo());
                    tableAddCell(table,fontsize08,inexpRlt.getInExpTime());
                }
                document.add(table);
            }*/

            table = new PdfPTable(1);
            cell = new PdfPCell();
            cell.setPhrase(new Paragraph(""));
            table.addCell(cell);
            table.setExtendLastRow(true);
            document.add(table);
        }
        document.close();
    }


    private static String dateToString(Date dateValue, String format) {
        if (dateValue == null || format == null) {
            return null;
        } else {
            SimpleDateFormat dateFormat = new SimpleDateFormat(format);
            return dateFormat.format(dateValue);
        }
    }
}